package org.bim.view.drag.design.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 获取地图数据工具类
 */
@Component
@Slf4j
public class MapDataAccessUtil {
    private static final String DATA_URL = "https://geo.datav.aliyun.com/areas_v3/bound/%s_full.json";
    private static final String REGEX_COUNTYR = "100000";

    private static final String REGEX_PROVINCE = "[1-9][0-9]0{4}";

    private static final String REGEX_CITY = "[1-9][0-9](0[1-9]|[1-9]0|[1-9][1-9])0{2}";

    private static final String REGEX_AREA = "[1-9][0-9](0[1-9]|[1-9]0|[1-9][1-9])(0[1-9]|[1-9]0|[1-9][1-9])";
    @Autowired
    private RestTemplate restTemplate;

    public JSONObject getDataByCode(String areaCode){
        if (!check(areaCode)) {
            return null;
        }
        String url = String.format(DATA_URL,areaCode);
        log.info("请求地址：{}",url);
        JSONObject result =null;
        try {
            result =restTemplate.getForObject(url,JSONObject.class);
        }catch (Exception e){
            log.error("获取区域数据失败",e);
        }
       return result;
    }

    private boolean check(String code) {
        if (code == null || "".equals(code)) {
            log.warn("区域编码不能为空");
            return false;
        }
        if (code.matches(REGEX_COUNTYR)) {
            return true;
        }
        if (code.matches(REGEX_PROVINCE)) {
            return true;
        }
        if (code.matches(REGEX_CITY)) {
            return true;
        }
        if (code.matches(REGEX_AREA)) {
            return true;
        }
        log.warn("区域编码不合法,{}", code);
        return false;
    }
}
